package com.eliota.config;

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author M.G
 * @create 2023-03-20 16:43
 * @date 2023/3/20 16:43
 *
 * 跨域设置
 */

@Configuration
public class GlobalCorsConfig implements WebMvcConfigurer {

    //跨域请求最大有效时间，1天
    private static final long MAX_AGE = 24*60*60;

    //http://localhost:8080
    @Bean
    public CorsFilter corsFilter() {
        //1. 添加 CORS配置信息
        CorsConfiguration config = new CorsConfiguration();
       /* config.addAllowedOrigin("http://localhost:8080");       //放行哪些原始域
        config.addAllowedOrigin("http://127.0.0.1:8080");       //放行哪些原始域
        config.addAllowedOrigin("http://192.168.173.206:8080");       //放行哪些原始域*/
        /*config.addAllowedOrigin("http://localhost:8080");       //放行哪些原始域*/
        config.addAllowedOriginPattern("*");
       /* config.addAllowedOrigin("*");       //放行哪些原始域*/
        config.setAllowCredentials(true);   //是否发送 Cookie
        config.addAllowedMethod("*");       //放行哪些请求方式
        config.addAllowedHeader("*");       //放行哪些原始请求头部信息
        config.addExposedHeader("*");       //暴露哪些头部信息
        config.setMaxAge(MAX_AGE);

        //2. 添加映射路径
        UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
        corsConfigurationSource.registerCorsConfiguration("/**",config);

        //3. 返回新的CorsFilter
        return new CorsFilter(corsConfigurationSource);
    }



/*    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 设置允许跨域的路由
        registry.addMapping("/**")
                // 设置允许跨域请求的域名------------修改此行
                .allowedOriginPatterns("*")
                // 是否允许证书（cookies）
                .allowCredentials(true)
                // 设置允许的方法
                .allowedMethods("*")
                // 跨域允许时间
                .maxAge(3600);
    }*/
}
